<script setup lang="ts">
  import { ref, computed, watch } from 'vue'
  import { StrUtil } from '@xtail/core'
  import { SizeUtil } from '@xtail/ui'
  import { WatchSizeStrategyConst, SWatchSize } from '../SWatchSize'
  import { GridResponsivePropsType } from './types'

  defineOptions({
    name: 'SGridResponsive'
  })

  const props = withDefaults(defineProps<GridResponsivePropsType>(), {
    strategy: WatchSizeStrategyConst.SELF,
    widthUpdateHandler: () => {},
    immediate: true,
    colsDefault: 1,
    colsUpdateHandler: () => {},
    rows: 'auto',
    gap: 0,
    colGap: 0,
    rowGap: 0
  })

  const gridCols = ref<string | number>(props.colsDefault)
  const gridTemplateColumns = ref<string>('auto')
  const handleWidthUpdate = (size: number) => {
    let cols: string | number = props.colsDefault
    if (props.widthBreakpoints && props.widthBreakpoints.length > 0) {
      for (let i = 0; i < props.widthBreakpoints.length; i++) {
        const breakpoint = props.widthBreakpoints[i]
        if (size <= breakpoint) {
          if (props.clos && props.clos.length > i) cols = props.clos[i]
          else if (props.clos && props.clos.length > 0) cols = props.clos[props.clos.length - 1]
        }
      }
    } else if (props.clos && props.clos.length > 0) cols = props.clos[0]
    gridCols.value = cols
    gridTemplateColumns.value = StrUtil.isStr(cols) ? cols : `repeat(${cols}, 1fr)`
    props.widthUpdateHandler(size)
  }
  watch(
    () => gridCols.value,
    () => {
      props.colsUpdateHandler(gridCols.value)
    },
    { immediate: props.immediate }
  )

  const gridTemplateRows = computed(() =>
    StrUtil.isStr(props.rows) ? props.rows : `repeat(${props.rows}, 1fr)`
  )
</script>

<template>
  <s-watch-size
    class="s-grid-responsive"
    :style="{
      gridTemplateColumns,
      gridTemplateRows,
      gap: SizeUtil.unitPreHandler(gap),
      columnGap: SizeUtil.unitPreHandler(colGap),
      rowGap: SizeUtil.unitPreHandler(rowGap)
    }"
    :strategy="strategy"
    :immediate="immediate"
    :width-update-handler="handleWidthUpdate"
  >
    <slot />
  </s-watch-size>
</template>

<style lang="scss">
  @use './style' as *;
</style>
